const RXJs = require('../library/reactivex/rx');
const config=require('../config.js');
const wechat = {
  getSession: require('./account').getSession,
  request: require('../wechat/network/request').request,
  upload: require('../wechat/network/request').upload,
};
const app = getApp();

const socket = ()=>{
  
}

const setHttp = (url, data, method = 'GET') => {
  app.observableId++;
  let id = app.observableId;
  let reactive = RXJs.subject(id);
  let cancel = false;
  reactive.cancel(() => {
    cancel = true;
  });
  wechat.getSession().then((session) => {
    if(cancel){
      reactive.fail('cancel');
      return;
    }
    let http = wechat.request({
      url:`${config.host.rest}${url}`,
      data,
      method,
      header: {
        Authorization: `SessionKey ${session}`
      }
    }).then((result)=>{
      reactive.success(result);
    }, (error)=>{
      reactive.fail(error);
    });

    reactive.cancel(() => {
      http.unsubscribe();
    });
  }, (error)=>{
    reactive.fail(error);
  });
  return RXJs.observable(id);
}


const upload = (opt) => {
  app.observableId++;
  let id = app.observableId;
  let reactive = RXJs.subject(id);
  let cancel = false;
  reactive.cancel(() => {
    cancel = true;
  });
  wechat.getSession().then((session) => {
    if(cancel){
      reactive.fail('cancel');
      return;
    }
    opt.header.Authorization = `SessionKey ${session}`
    let http = wechat.upload(opt)
      .subscribe((data)=>{
        reactive.next(data)
      },(err)=>{
        reactive.error(err)
      }).then((result)=>{
        reactive.success(result);
      }, (error)=>{
        reactive.fail(error);
      });

    reactive.cancel(() => {
      http.unsubscribe();
    });
  }, (error)=>{
    reactive.fail(error);
  });
  return RXJs.observable(id);
}

module.exports = {
	setHttp,
  upload
}

